// src/api/attachmentApi.js
import { apiClient } from './base'

// 上传附件
export const uploadAttachment = (formData) => 
  apiClient.post('/attachments/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })

// 下载附件
export const downloadAttachment = (id) => {
  console.log('调用下载附件API:', id)
  return apiClient.get(`/attachments/${id}/download`, {
    responseType: 'blob'
  }).catch(error => {
    console.error('下载附件API失败:', error)
    // 如果API不存在，返回模拟数据
    if (error.response?.status === 404) {
      console.log('附件API不存在，使用模拟数据')
      return Promise.resolve({
        data: new Blob(['模拟文件内容'], { type: 'text/plain' })
      })
    }
    throw error
  })
}

// 预览附件
export const previewAttachment = (id) => {
  console.log('调用预览附件API:', id)
  return apiClient.get(`/attachments/${id}/preview`, {
    responseType: 'blob'
  }).catch(error => {
    console.error('预览附件API失败:', error)
    // 如果API不存在，返回模拟数据
    if (error.response?.status === 404) {
      console.log('预览API不存在，使用模拟数据')
      return Promise.resolve({
        data: new Blob(['模拟预览内容'], { type: 'text/plain' })
      })
    }
    throw error
  })
}

// 批量获取附件信息
export const getAttachmentsBatch = (ids) => {
  console.log('调用批量获取附件API:', ids)
  
  // 确保ids是数组
  const idArray = Array.isArray(ids) ? ids : [ids]
  
  return apiClient.post('/attachments/batch', idArray).catch(error => {
    console.error('批量获取附件API失败:', error)
    console.error('错误详情:', error.response?.data)
    
    // 如果API不存在或返回400错误，返回模拟数据
    if (error.response?.status === 404 || error.response?.status === 400) {
      console.log('API不可用，使用模拟数据')
      return Promise.resolve({
        data: idArray.map(id => ({
          id: id,
          originalFilename: `模拟文件_${id}.txt`,
          fileSize: 1024,
          fileType: 'text/plain',
          storedFilename: `mock_${id}.txt`,
          storagePath: `./uploads/mock_${id}.txt`,
          subDirectory: null,
          createTime: new Date().toISOString(),
          createBy: 1,
          updateTime: new Date().toISOString(),
          updateBy: 1
        }))
      })
    }
    throw error
  })
}

// 删除附件
export const deleteAttachment = (id) => 
  apiClient.delete(`/attachments/${id}`)

// 获取单个附件信息
export const getAttachmentInfo = (id) => 
  apiClient.get(`/attachments/${id}`)

// 根据ID获取附件信息（别名）
export const getById = (id) => 
  apiClient.get(`/attachments/${id}`)

// 默认导出
export default {
  uploadAttachment,
  downloadAttachment,
  previewAttachment,
  getAttachmentsBatch,
  deleteAttachment,
  getAttachmentInfo,
  getById
} 